<template>

  <div class="product-detail-container">
    <!-- 商品详情顶部内容 -->
    <SkeletonLoader v-if="!detailData || !detailData.id" :type="'product-card'"></SkeletonLoader>
    <ProductDetailTop.default v-else :detailData="detailData" :comments="comments" @buy="handleBuy" />

    <!-- 评价-->
    <SkeletonLoader v-if="!isLoading" :type="'comment'"></SkeletonLoader>
    <template v-else>
      <CustomerReview v-if="!isLoggedIn" @write-review="handleWriteReview"></CustomerReview>
      <Comment.default v-if="isLoggedIn && comments.length > 0" :comments="comments" @like="handleCommentLike"
        @dislike="handleCommentDislike" />
    </template>


    <!-- 顾客还浏览了 -->
    <SkeletonLoader v-if="!relatedGoods" :type="'carousel'"></SkeletonLoader>
    <CategoryImage :title="'RELATED PRODUCTS'" :options="relatedGoods" v-else />


    <!-- 最近浏览 -->
    <SkeletonLoader v-if="recentlyViewedItems.length === 0" :type="'carousel'"></SkeletonLoader>
    <CategoryImage :title="'RECENTLY VIEWED PRODUCTS'" :options="recentlyViewedItems" v-else />

  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import * as ProductDetailTop from './components/ProductDetailTop.vue';
import * as Comment from '@/components/Comment.vue';
import { getDetail, addVisit, addCart } from '@/api/goods';
import { Local } from "@/utils/storage";
import { timeFormat, addUniqueItemById } from '@/utils/common';
import SkeletonLoader from './components/SkeletonLoader.vue';
import mitt from '@/utils/mitt';
import { useCartStore } from '@/store/cart';
import CategoryImage from '@/components/CategoryImage.vue';
import CustomerReview from './components/CustomerReview.vue';
import { getUserToken } from '@/utils/cache'; // 引入新的Token获取函数

const route = useRoute()
const router = useRouter()

import Carousel from '@/components/Carousel.vue';
import { message } from 'ant-design-vue';
import { options } from 'marked';

const cartStore = useCartStore()
// 首先定义类型接口
interface GoodsDetail {
  id: number;
  name: string;
  url: string;
  min_price: number;
  detail_images: string[];
  viewedDate?: string;
  is_favorited?: number;
  skuId?: number;
  price?: number;
  description?: string;
  spec_list?: any[];
}

interface RelatedGood {
  id: number;
  name: string;
  url: string;
  min_price: number;
  detail_images: string[];
}

interface Comment {
  id: number | string;
  author: string;
  avatar: string;
  content: string;
  datetime: string | Date;
  rating?: number;
  likes?: number;
  dislikes?: number;
  action?: 'liked' | 'disliked' | undefined;
}

// 评论数据
const comments = ref<Comment[]>([]);

// 风格轮播数据
const carouselItems = ref<any>(null);

// 最近浏览数据
const recentlyViewedItems = ref<GoodsDetail[]>([]);


//商品详情
const detailData = ref<GoodsDetail>({} as GoodsDetail);

let relatedGoods = ref<any>(null);
let isLoading = ref(false)
//获取商品详情
const getDetailData = async () => {
  try {
    // const res = await getDetail(route.query.id as string);
    // const data = res.result;
    // console.log(data, "商品详情")
    const data = (window as any).__INITIAL_PRODUCT__?.productdetails;
    // console.log((window as any).__INITIAL_PRODUCT__, "996")
    if (!data) {
      throw new Error('No product data available');
    }

    isLoading.value = true;
    detailData.value = data.goods_detail;
    relatedGoods.value = data.related_goods.map((item: any) => ({
      id: item.id,
      title: item.name,
      price: item.min_price,
      origin_price: item.min_origin_price,
      url: item.url,
      image: item.detail_images[0],
      hoverImage: item.detail_images[1],
      //判断折扣的 discount_enabled === 1 说明有折扣，则取折扣字段discount
      badge: data.goods_detail.discount_enabled === 1 ? `-${data.goods_detail.discount}% OFF` : '',
      isWishlist: item.is_favorited,
      inventory: data.goods_detail.total_stock,
    }));;
    comments.value = data.goods_comments;
    carouselItems.value = data.hot_goods;
    // 使用类型断言确保类型安全
    // const responseData = data.result as GoodsDetail;
    // detailData.value = responseData.goods_detail || null;
    // relatedGoods.value = responseData.related_goods
    // .map((item: any) => ({
    //   id: item.id,
    //   title: item.name,
    //   price: item.min_price,
    //   origin_price: item.min_origin_price,
    //   image: item.detail_images[0],
    //   hoverImage: item.detail_images[1],
    //   //判断折扣的 discount_enabled === 1 说明有折扣，则取折扣字段discount
    //   badge: responseData.goods_detail.discount_enabled === 1 ? `-${responseData.goods_detail.discount}% OFF` : '',
    //   isWishlist: responseData.goods_detail.favorite,
    //   inventory: responseData.goods_detail.total_stock,
    // }));
    // comments.value = responseData.goods_comments || [];
    // carouselItems.value = responseData.hot_goods || [];

    // 处理浏览历史
    if (data.goods_detail) {
      await handleViewHistory(data.goods_detail);
    }

    // 更新收藏状态
    updateFavoritesStatus();
  } catch (error) {
    console.error('Failed to load product details:', error);
    // message.error('Failed to load product details');
  }
}

// 处理浏览历史
const handleViewHistory = async (goodsDetail: GoodsDetail) => {
  try {
    // 从本地存储获取已存在的浏览历史
    const storedHistory = Local.get('recentlyViewed') || [];

    // 检查是否已存在相同ID的商品
    const isExist = storedHistory.some((item: any) => item.id === goodsDetail.id);

    // 如果不存在，则添加到历史记录中
    if (!isExist) {
      // 转换为存储格式
      const formattedItem = {
        id: goodsDetail.id,
        title: goodsDetail.name,
        price: goodsDetail.min_price,
        url:goodsDetail.url,
        origin_price: goodsDetail.min_origin_price,
        image: goodsDetail.detail_images[0],
        hoverImage: goodsDetail.detail_images.length > 1 ? goodsDetail.detail_images[1] : goodsDetail.detail_images[0],
        badge: goodsDetail.discount_enabled === 1 ? `-${goodsDetail.discount}% OFF` : '',
        isWishlist: goodsDetail.favorite,
        inventory: goodsDetail.total_stock,
        viewedDate: timeFormat() // 添加浏览时间
      };

      // 将当前商品添加到本地存储的浏览历史中
      const updatedHistory = [...storedHistory, formattedItem];

      // 限制历史记录数量，保留最新的20条
      const limitedHistory = updatedHistory.slice(-20);

      // 保存到本地存储
      Local.set('recentlyViewed', limitedHistory);

      // 更新组件中的数据
      recentlyViewedItems.value = limitedHistory.reverse();
    } else {
      // 如果已存在，只更新时间并将其移到最近
      const updatedHistory = storedHistory.filter((item: any) => item.id !== goodsDetail.id);
      const existingItem = storedHistory.find((item: any) => item.id === goodsDetail.id);
      if (existingItem) {
        existingItem.viewedDate = timeFormat();
        updatedHistory.unshift(existingItem);

        // 保存到本地存储
        Local.set('recentlyViewed', updatedHistory);

        // 更新组件中的数据
        recentlyViewedItems.value = updatedHistory.reverse();
      }
    }
  } catch (error) {
    console.error('Failed to handle view history:', error);
  }
}

// 更新收藏状态
const updateFavoritesStatus = () => {
  try {
    // 如果detailData为null，退出函数
    if (!detailData.value) {
      return;
    }

    // 使用类型断言来处理可能不存在的方法
    const collectedItems = (cartStore as any).getCollect();
    if (!collectedItems?.length) return;

    // 创建一个新对象合并属性，避免直接修改引用
    detailData.value = {
      ...detailData.value,
      is_favorited: collectedItems.some((item: any) => item.goods_id === detailData.value?.id) ? 1 : 0
    };
  } catch (error) {
    console.error('Failed to update favorites status:', error);
  }
}

onMounted(() => {
  getDetailData();
  // Check login status
  checkLoginStatus();
});

// Add this near other refs
const isLoggedIn = ref(false);

// Add this method to handle review writing
const handleWriteReview = () => {
  // If user is not logged in, redirect to login page or show login modal
  if (!isLoggedIn.value) {
    // Redirect to login page or show login modal
    message.error('Please log in to write a review');
    // You can replace this with actual navigation to login page or showing a login modal
  }
};

// Add this method to get login status
const checkLoginStatus = () => {
  // Replace this with your actual authentication check logic
  // For example, checking a token in localStorage or using your auth store
  const token = getUserToken;
  isLoggedIn.value = !!token;
};

// 方法定义
const handleCarouselItemClick = (item: RelatedGood) => {
  router.push(`/product/${item.url}.html`);
};

const handleClearHistory = () => {
  router.push('/user/history');
};

const handleCommentLike = (index: number) => {
  if (!comments.value[index]) return;

  const comment = comments.value[index];
  comment.action = 'liked';
  comment.like_count = (comment.like_count || 0) + 1;
  comment.dislikes = 0;
};

const handleCommentDislike = (index: number) => {
  if (!comments.value[index]) return;

  const comment = comments.value[index];
  comment.action = 'disliked';
  comment.dislikes = (comment.dislikes || 0) + 1;
  comment.likes = 0;
};

const handleBuy = async (product: GoodsDetail) => {
  try {
    if (!product || !product.skuId) {
      throw new Error('Invalid product SKU');
    }

    const response = await addCart({
      sku_id: product.skuId,
      num: product.quantity || 1
    });

    // 使用类型断言处理响应
    const responseData = response as any;
    if (responseData.code === 200) {
      message.success('Successfully added to shopping cart');
      mitt.emit('addShoppingCart');
    } else {
      throw new Error(responseData.message || 'Failed to add to cart');
    }
  } catch (error) {
    console.error('Failed to add to cart:', error);
    message.error('Failed to add to cart');
  }
};

</script>

<style lang="scss" scoped>
.product-detail-container {
  padding: 20px 15px;
  max-width: 1540px;
  margin: 0 auto;

  @media (min-width: 768px) {
    padding: 20px 30px;
  }
}

.recently-viewed {
  margin-top: 70px;
}
</style>